package com.dfl.ggbond.pic.adpter;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.dfl.ggbond.R;
import com.dfl.ggbond.media.MediaInfo;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class PictureAdapter extends RecyclerView.Adapter<PictureAdapter.MyViewHolder> {

    private final Context context;
    private List<MediaInfo> mediaList;
    private boolean isGrid;
    private final LayoutInflater inflater;

    public View.OnClickListener onItemClick;

    public PictureAdapter(Context context, List<MediaInfo> mediaList, boolean isGrid) {
        this.context = context;
        this.mediaList = mediaList;
        this.isGrid = isGrid;
        this.inflater = LayoutInflater.from(context);
    }

    public void setData(List<MediaInfo> list) {
        this.mediaList = list;
        notifyDataSetChanged();
    }

    public void setDisplayMode(boolean isGrid) {
        this.isGrid = isGrid;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = inflater.inflate(R.layout.picture_recylerview_layout, parent, false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        MediaInfo info = (mediaList != null && position < mediaList.size()) ? mediaList.get(position) : null;
        holder.bind(info);
    }

    @Override
    public int getItemCount() {
        return mediaList == null ? 0 : mediaList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView nameTv;
        TextView sizeTv;
        TextView ctTv;
        LinearLayout container;

        MyViewHolder(@NonNull View itemView) {
            super(itemView);
            container = itemView.findViewById(R.id.pic_item);
            imageView = itemView.findViewById(R.id.pic_img);
            nameTv = itemView.findViewById(R.id.pic_name);
            sizeTv = itemView.findViewById(R.id.pic_size);
            ctTv = itemView.findViewById(R.id.pic_ct);

            itemView.setOnClickListener(v -> {
                int pos = getAdapterPosition();
                if (pos != RecyclerView.NO_POSITION && mediaList != null && pos < mediaList.size()) {
                    if (onItemClick != null) {
                        v.setTag(mediaList.get(pos).getUri().toString());
                        onItemClick.onClick(v);
                    }
                }
            });
        }

        void bind(MediaInfo info) {
            if (isGrid) {
                hideTextViews();
                setImageSizeForParent(imageView, true);
            } else {
                showTextViews();
                setImageSizeForParent(imageView, false);
            }

            if (info == null) {
                imageView.setImageResource(R.drawable.ic_home_doc);
                if (nameTv != null) nameTv.setText("");
                if (sizeTv != null) sizeTv.setText("");
                if (ctTv != null) ctTv.setText("");
                return;
            }

            if (nameTv != null) nameTv.setText(info.getName() != null ? info.getName() : "");
            if (sizeTv != null)
                sizeTv.setText(info.getSize() > 0 ? formatSize(info.getSize()) : "");
            long time = info.getDataModified() > 0 ? info.getDataModified() * 1000L : (info.getDataAdded() > 0 ? info.getDataAdded() * 1000L : 0L);
            if (ctTv != null) ctTv.setText(time > 0 ? formatDate(time) : "");

            // 加载图片
            try {
                Uri loadUri = info.getUri();
                Glide.with(context)
                        .load(loadUri)
                        .centerCrop()
                        .placeholder(R.drawable.ic_home_doc)
                        .into(imageView);
            } catch (Throwable t) {
                try {
                    imageView.setImageURI(info.getUri());
                } catch (Exception ignored) {
                    imageView.setImageResource(R.drawable.ic_home_doc);
                }
            }
        }

        private void hideTextViews() {
            if (nameTv != null) nameTv.setVisibility(View.GONE);
            if (sizeTv != null) sizeTv.setVisibility(View.GONE);
            if (ctTv != null) ctTv.setVisibility(View.GONE);
        }

        private void showTextViews() {
            if (nameTv != null) nameTv.setVisibility(View.VISIBLE);
            if (sizeTv != null) sizeTv.setVisibility(View.VISIBLE);
            if (ctTv != null) ctTv.setVisibility(View.VISIBLE);
        }

        private void setImageSizeForParent(ImageView iv, boolean grid) {
            ViewGroup.LayoutParams lp = iv.getLayoutParams();
            if (lp instanceof LinearLayout.LayoutParams) {
                LinearLayout.LayoutParams llp = (LinearLayout.LayoutParams) lp;
                if (grid) {
                    llp.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    llp.height = dpToPx(120);
                } else {
                    llp.width = dpToPx(80);
                    llp.height = dpToPx(80);
                }
                iv.setLayoutParams(llp);
            } else {
                if (grid) {
                    lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    lp.height = dpToPx(120);
                } else {
                    lp.width = dpToPx(60);
                    lp.height = dpToPx(80);
                }
                iv.setLayoutParams(lp);
            }
        }

        private int dpToPx(int dp) {
            float density = context.getResources().getDisplayMetrics().density;
            return Math.round(dp * density);
        }

        private String formatSize(long size) {
            if (size <= 0) return "";
            final String[] units = {"B", "KB", "MB", "GB"};
            int idx = 0;
            double s = size;
            while (s >= 1024 && idx < units.length - 1) {
                s /= 1024.0;
                idx++;
            }
            return String.format(Locale.getDefault(), "%.1f %s", s, units[idx]);
        }

        private String formatDate(long millis) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
                return sdf.format(new Date(millis));
            } catch (Exception e) {
                return "";
            }
        }
    }
}